package org.aurora.module.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aurora.framework.boot.common.rpc.response.RpcResponse;
import org.aurora.module.user.api.facade.UserFacadeService;
import org.aurora.module.user.api.facade.request.UserRequest;
import org.aurora.module.user.api.facade.response.UserAuthResponse;
import org.aurora.module.user.api.facade.response.data.UserInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * AuthController
 * <pre>
 * description:
 * create date: 2025-03-16 17:20:50
 * </pre>
 *
 * @author cao.yong
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @DubboReference(version = "1.0.0")
    private UserFacadeService userFacadeService;

    @GetMapping("/username/login")
    public SaResult usernameLogin(String name, String password) {
        UserRequest userRequest = UserRequest.builder().username(name).password(password).build();
        RpcResponse response = userFacadeService.authByUsername(userRequest);
        return authLogin(response);
    }


    @GetMapping("/telephone/login")
    public SaResult telephoneLogin(String telephone, String password) {
        UserRequest userRequest = UserRequest.builder().telephone(telephone).password(password).build();
        RpcResponse response = userFacadeService.authByTelephone(userRequest);
        return authLogin(response);
    }

    @GetMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }

    private SaResult authLogin(RpcResponse response) {
        if (response.isSuccess()) {
            UserAuthResponse authResponse = (UserAuthResponse) response;
            UserInfo userInfo = authResponse.getData();
            StpUtil.login(userInfo.getId());
            return SaResult.ok("登录成功");
        }
        return SaResult.code(response.getCode()).setMsg(response.getMessage());
    }
}
